import React, { forwardRef, useEffect, useRef, useState } from "react";
import { Icon, Input, Popup, Keyboard, Picker, Toast } from "zarm";
import { typeMap } from "@/utils";
import s from "./style.module.less";
import CustomIcon from "../CustomIcon";
import cx from "classnames";
import PopupDate from "../PopupDate";
import dayjs from "dayjs";
import { get, post } from "@/utils";

// 父组件使用 ref，子组件需要使用 forwardRef  搭配
const PopupAdd = forwardRef(({ onSelect }, ref) => {
  const [show, setShow] = useState(false);
  const [payType, setPayType] = useState("expense"); //支出 或 收入
  const [date, setDate] = useState(new Date()); //riqi
  const [amount, setAmount] = useState(""); //金额
  const [expenseType, setExpenseType] = useState([]); //支出的类别
  const [incomeType, setIncomeType] = useState([]); //收入的类别
  const [currentType, setCurrentType] = useState({
    id: 11,
  }); //选择的账单类别
  const [remark, setRemark] = useState(""); //备注
  const [showRemark, setShowRemark] = useState(false); // 备注输入框

  const [payTool, setPayTool] = useState("支付宝"); //支出工具（支付宝、微信）
  const [showPayTool, setShowPayTool] = useState(false);

  // 支付方式列表
  const PAYTOOL_TYPE = [
    //数据源
    { value: "1", label: "现金" },
    { value: "2", label: "储存卡" },
    { value: "3", label: "信用卡" },
    { value: "4", label: "支付宝" },
    { value: "5", label: "微信钱包" },
    { value: "6", label: "蚂蚁花呗" },
  ];

  const dateRef = useRef();

  //   如果父组件通过ref绑定了子组件
  if (ref) {
    // 那么子组件就会在 ref 上挂一个 current 的值
    ref.current = {
      show: () => {
        setShow(true);
      },
      close: () => {
        setShow(false);
      },
    };
  }

  // 载入的时候进行类别请求
  useEffect(async () => {
    const {
      data: { list },
    } = await get("/api/type/list");
    if (list) {
      console.log("请求类型数据成功", list);
    } else {
      console.log("请求类型数据失败!");
      return
    }

    //筛选放置请求到的数据          filter  过滤出当前数组中满足条件的数据，且返回一个新的数组
    setExpenseType(list.filter((i) => i.type == 1));
    setIncomeType(list.filter((i) => i.type == 2));
  }, []);

  //   在选择账目类别的时候触发
  const changeType = (type) => {
    setPayType(type);
    setCurrentType(type == "expense" ? expenseType[0] : incomeType[0]);
  };

  //   控制选择时间的浮层
  const handleDatePop = () => {
    dateRef.current && dateRef.current.show();
  };
  //   设置选择的时间
  const selectDate = (val) => {
    setDate(val);
    // ??????为什么这里不能正常打印，但是提交的是正确的数据？？？？
    console.log("我已经在添加新账单这里选择了时间", val);
  };

  // 获取到选定的类别
  const choseType = (item) => {
    console.log(item);
    setCurrentType(item);
  };

  // 提交账单
  const addBill = async () => {
    console.log(
      "准备提交账单,看看这些东西有没有录入吧(支出还是收入、途径、时间、金额、具体类别、备注)",
      payType,
      payTool,
      date,
      amount,
      currentType,
      remark
    );
    console.log('111',date instanceof Date,date);
    // 准备提交数据了
    const newBill = {
      pay_type: payType == "expense" ? 1 : 2,
      amount: amount,
      date: date.getTime(),
      type_id: currentType.id,
      type_name: currentType.name,
      remark: remark,
      pay_tool: payTool,
    };
    console.log('222');
    // 提交数据
    const { data } = await post("/api/bill/addBill", { newBill });
    console.log("这是创建新账单的请求回调", data);
    if (data) {
      setPayType("expense"); //重置类型
      setAmount(""); //重置金钱
      setCurrentType({ id: 11 }); //重置选定类型
      setRemark(""); //重置备注
      setPayTool("支付宝"); //重置付款工具

      Toast.show("添加成功");

      setShow(false);
      // 让首页刷新
      onSelect();
      return;
    }
  };

  // 计算器计算
  const handleMoney = (value) => {
    value = String(value);

    if (value == "close") return;

    // 点击的是删除按钮时
    if (value == "delete") {
      let _amount = amount.slice(0, amount.length - 1);
      setAmount(_amount);
      return;
    }

    // 点击确定按钮时
    if (value == "ok") {
      if (amount == 0) {
        Toast.show("您还没有输入金额哦~");
        return;
      }
      addBill();
      return;
    }

    // 当输入的值为 '.' 且 已经存在 '.' 时，则不让其继续字符串相加
    if (value == "." && amount.includes(".")) {
      return;
    }

    // 小数点后保留两位，当超过两位时，不让其字符串相加
    if (
      value != "." &&
      amount.includes(".") &&
      amount &&
      amount.split(".")[1].length >= 2
    )
      return;

    // 正常字符串拼接
    setAmount(amount + value);
  };

  return (
    <Popup
      visible={show}
      onMaskClick={() => setShow(false)}
      //   direction="bottom"
      //   destroy={false}
    >
      <div className={s.addItem}>
        <header className={s.header}>
          <span className={s.close} onClick={() => setShow(false)}>
            <Icon type="wrong"></Icon>
          </span>
        </header>
        <div className={s.filter}>
          <div className={s.type}>
            <span
              onClick={() => changeType("expense")}
              className={cx({
                [s.expense]: true,
                [s.active]: payType == "expense",
              })}
            >
              支出
            </span>
            <span
              onClick={() => changeType("income")}
              className={cx({
                [s.income]: true,
                [s.active]: payType == "income",
              })}
            >
              收入
            </span>
          </div>
          {/* 选择支出/收入途径 */}
          <div className={s.payWay} onClick={() => setShowPayTool(true)}>
            {payTool}
            <Icon className={s.arrow} type="arrow-bottom"></Icon>
          </div>
          {/* 选择支出/收入地点 */}
          {/* <div className={s.address}>
            地点
            <Icon className={s.arrow} type="arrow-bottom"></Icon>
          </div> */}

          {/* 选择支出/收入时间 */}
          <div className={s.time} onClick={handleDatePop}>
            {dayjs(date).format("MM-DD")}
            <Icon className={s.arrow} type="arrow-bottom"></Icon>
          </div>
        </div>
        {/* 金额展示 */}
        <div className={s.money}>
          <span className={s.moneyType}>
            {currentType.name ? currentType.name : "类别"}
          </span>
          <span className={cx(s.amount, s.animation)}>{amount}</span>
        </div>

        {/* 类别展示 */}
        <div className={s.typeWarp}>
          <div className={s.typeBody}>
            {(payType == "expense" ? expenseType : incomeType).map((item) => (
              <div
                onClick={() => choseType(item)}
                key={item.id}
                className={s.typeItem}
              >
                <span
                  className={cx({
                    [s.iconfontWrap]: true,
                    [s.expense]: payType == "expense",
                    [s.income]: payType == "income",
                    [s.active]: currentType.id == item.id,
                  })}
                >
                  <CustomIcon
                    className={s.iconfont}
                    type={typeMap[item.id].icon}
                  />
                </span>
                <span>{item.name}</span>
              </div>
            ))}
          </div>
        </div>

        {/* 备注 */}
        <div className={s.remark}>
          {showRemark ? (
            <Input
              autoHeight
              showLength
              maxLength={50}
              text="text"
              rows={3}
              value={remark}
              placeholder="请输入备注信息"
              onChange={(val) => setRemark(val)}
              onBlur={() => setShowRemark(false)}
            ></Input>
          ) : (
            <span onClick={() => setShowRemark(true)}>
              {remark || "添加备注"}
            </span>
          )}
        </div>

        {/* 计算器 */}
        <Keyboard type="price" onKeyClick={(value) => handleMoney(value)} />

        {/* 时间浮层 */}
        <PopupDate ref={dateRef} onSelect={selectDate} />

        {/* 支付工具选择浮层 */}
        <Picker
          visible={showPayTool} //是否展示
          value={""} //值
          dataSource={PAYTOOL_TYPE}
          onOk={(value) => {
            //点击确定时触发的回调函数
            console.log("222222222", value);
            setPayTool(value[0].label);
            console.log("222hh", payTool);
            setShowPayTool(false);
          }}
          onCancel={() => {
            //点击取消时触发的回调函数
            setShowPayTool(false);
          }}
        />

        {/* 支付地点选择 */}
        {/* 这个之后作为拓展 */}
      </div>
    </Popup>
  );
});

export default PopupAdd;
